import { createRouter, createWebHashHistory } from 'vue-router'
import { h } from 'vue'
import store from '@/store'
const Layout = () => import('@/views/layout')
const home = () => import('@/views/home')
const topcategory = () => import('@/views/category/index.vue')
const subcategory = () => import('@/views/category/sub.vue')
const goods = () => import('@/views/goods/index.vue')
const login = () => import('@/views/login/index.vue')
const logincallback = () => import('@/views/login/login-callback.vue')
const cart = () => import('@/views/cart/index.vue')
const checkout = () => import('@/views/member/pay/checkout.vue')
const memberpay = () => import('@/views/member/pay/index.vue')
const result = () => import('@/views/member/pay/result.vue')
const Memberlayout = () => import('@/views/member/Layout.vue')
const MemberHome = () => import('@/views/member/home')
const Memberorder = () => import('@/views/member/order/index.vue')
const Memberorderdetail = () => import('@/views/member/order/detail.vue')

const routes = [
  {
    path: '/',
    component: Layout,
    children: [
      {
        path: '/',
        component: home
      },
      {
        path: '/category/:id',
        component: topcategory
      },
      {
        path: '/category/sub/:id',
        component: subcategory
      },
      {
        path: '/product/:id',
        component: goods
      },
      {
        path: '/cart',
        component: cart
      },
      {
        path: '/member/checkout',
        component: checkout
      },
      {
        path: '/member/pay',
        component: memberpay
      },
      {
        path: '/pay/callback',
        component: result
      },
      {
        path: '/member',
        component: Memberlayout,
        children: [
          {
            path: '/member',
            component: MemberHome
          },
          {
            path: '/member/order',
            component: { render: () => h(<RouterView />) },
            // 注意此处必须使用嵌套，否则active-class不生效
            children: [
              {
                path: '',
                component: Memberorder
              },
              {
                path: ':id',
                component: Memberorderdetail
              }
            ]
          }
        ]
      }
    ]
  },
  {
    path: '/login',
    component: login
  },
  {
    path: '/login/callback',
    component: logincallback
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
  scrollBehavior () {
    return { left: 0, top: 0 }
  }
})

// 前置导航守卫
router.beforeEach((to, from, next) => {
  // 需要登录的路由：地址是以 /member 开头
  const { profile } = store.state.user
  if (!profile.token && to.path && to.path.startsWith('/member')) {
    return next('/login?redirectUrl=' + encodeURIComponent(to.fullPath))
  }
  next()
})

export default router
